//
//  WBNetworkManager.swift
//  XLWB
//
//  Created by MacBook on 16/7/2.
//  Copyright © 2016年 MacBook. All rights reserved.
//

import UIKit
import AFNetworking

//swift中枚举支持任意数据类型

enum WBHTTPMethod {

    case GET
    case POST
}

class WBNetworkManager: AFHTTPSessionManager {

    //在第一次访问时,执行闭包,并且将结果保存在shared常量中
//    static let shared = WBNetworkManager()
    static let shared: WBNetworkManager = {
    //实例化对象
        let instance = WBNetworkManager()
        
        //设置相应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    
    
    }()
    
//    //访问令牌,所有的网络请求都需要令牌,(登录除外)
//    var accessToken: String?  //= "2.00C9TPVGuOjD9Cb544314787d9ND1D"
//    
//    //用户微博id
//    var uid: String? = "5958551542"
    //用户账户的懒加载属性
    lazy var userAccount = WBUserAccount()
    
    //用户登录标记[计算属性]
    var userLogon: Bool {
    
        return userAccount.access_token != nil
    
    }
    
    //负责拼接token的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,  name: String? = nil, data: Data? = nil, completion: (json: AnyObject?, isSuccess: Bool)->()) {
    
        //处理token字典
        guard let token = userAccount.access_token else {
            print("token不存在!请重新登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            completion(json: nil, isSuccess: false)
            return
        }
    
        //判断参数字典是否存在,如果为nil,应新建一个字典
        var parameters = parameters
        if parameters == nil {
            
            parameters = [String: AnyObject]()
        }
    
        parameters!["access_token"] = token
        
        //调用request发起网络请求的方法

//        request(method: method, URLString: URLString, parameters: parameters, completion: completion)

        if let name = name, data = data {
            // 上传文件
            upload(URLString: URLString, parameters: parameters, name: name, data: data, completion: completion)
        } else {
            
            // 调用 request 发起真正的网络请求方法
            
            request(method: method, URLString: URLString, parameters: parameters, completion: completion)
        }

    }
    
    //上传文件
    func upload(URLString: String, parameters: [String: AnyObject]?, name: String, data: Data, completion: (json: AnyObject?, isSuccess: Bool)->()) {
    
        post(URLString,parameters: parameters, constructingBodyWith: { (formData) in
        
             formData.appendPart(withFileData: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")

            }, progress: nil, success: { (_, json) in
                
                completion(json: json, isSuccess:  true)
                
        }) { (task, error) in
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
            print("Token 过期")
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                    object: "bad token")

            
            }
        
            print("网络请求错误 \(error)")
            completion(json: nil, isSuccess: false)
        
        
        }
    }

    
    
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?, completion:(json: AnyObject?, isSuccess: Bool)->()) {
    
        let success = { (task: URLSessionDataTask, json: AnyObject?)->() in
        
            //成功回调
        completion(json: json, isSuccess: true)
        
        }
        
            //失败回调
        let failure = { (task: URLSessionDataTask?,error: NSError)->() in
            
            //模拟token过期,默认三天
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                print("token已过期,请重新注册")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
            }
            
            
            print("网络请求错误\(error)")
            
            completion(json: nil, isSuccess: false)
    
        }
    
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
        
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
    
        }
    }
}
